package test;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class ImgPanel extends JPanel {
	private Image img;
	public ImgPanel (String imgPath){
		img= new ImageIcon(imgPath).getImage();
	}
	public void paintComponent(Graphics g){
		Graphics2D g2 = (Graphics2D) g;
		//panel width height
		int pw=this.getWidth();
		int ph=this.getHeight();
		//img width height
		int iw=img.getWidth(null);
		int ih=img.getHeight(null);
//		img缩放后的宽度和高度
		int w=iw*ph/ih;
		int h = ih*pw/iw;
		//显示原图
		if(iw<pw&&ih<ph){
			g2.drawImage(img,0,0,iw,ih,null);
		}
		//确定以高，宽中的哪个缩放
		else if(w>pw){
			g2.drawImage(img,0,0,pw,h,null);
		}else if(h>ph){
			g2.drawImage(img,0,0,w,ph,null);
		}
		//可以现时画多个较重图片
//		Image img= new ImageIcon("/home/tarena/Pictures/3.jpg").getImage();
//		g2.drawImage(img, 10, 10, null);
		
	}
}
